<template>
    <view>
        <ca-switch
            :modelValue="initName(curValue)"
            :size="size"
            :readonly="readOnly"
            :on-text="checkedChildren"
            :off-text="unCheckedChildren"
            :desMethod="metadata.options.desMethod"
            :textSize="22"
            @change="onChange"
        ></ca-switch>
    </view>
</template>

<script>
/**
 * 开关
 * https://ext.dcloud.net.cn/plugin?id=12009
 */
import MForm from "../js/MForm";

export default {
    name: "MSwitch",
    mixins: [MForm],
    components: {},
    props: {},
    data() {
        return {
            curValue: false,
            trueVal:true,
            falseVal:false,
        }
    },
    computed: {
        size() {
            if(this.metadata.options.size == "small"){
                return 36;
            }
            return 44;
        },
        checkedChildren() {
            return this.metadata.options.checkedChildren;
        },
        unCheckedChildren() {
            return this.metadata.options.unCheckedChildren;
        },
    },
    created() {
        //自定义值
        if(this.metadata.options.valueSource=="custom"){
            this.trueVal = this.metadata.options.trueVal ;
            this.falseVal = this.metadata.options.falseVal ;
        }
        this.initValue(this.value);
    },
    methods: {
        initName(val){
            if(typeof val === 'string'){
                return JSON.parse(val)
            }
            return  val
        },
        initValue(value){
            let val="";
            //自定义值
            if(this.metadata.options.valueSource=="custom"){
                let trueVal = this.metadata.options.trueVal ;
                val=value==trueVal?'true':'false';
            }else {
                val=JSON.parse(value);
            }
            if(typeof val === 'boolean'){
                val = JSON.stringify(val)
            }
            this.curValue=val;
        },
        onChange(value){
            let val="";
            //自定义值
            if(this.metadata.options.valueSource=="custom"){
                let trueVal = this.metadata.options.trueVal ;
                let falseVal = this.metadata.options.falseVal ;
                val=value?trueVal:falseVal;
            }else {
                val=value;
            }
            if(typeof val === 'boolean'){
                val = JSON.stringify(val)
            }
            this.setData(val);
        }
    },
    watch: {
        value(val) {
            this.initValue(val);
        }
    },
}
</script>

<style scoped>

</style>
